package com.jingdianjichi.project.infra.config;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jingdianjichi.project.common.utils.LoginUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;


import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.*;


@Component
@Slf4j
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class MybatisInterceptor implements Interceptor {


    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        Object parameter = invocation.getArgs()[1];
        String loginId = LoginUtil.getLoginId();


        if (StringUtils.isBlank(loginId)) {
            return invocation.proceed();
        }


        if (sqlCommandType == SqlCommandType.UPDATE || sqlCommandType == SqlCommandType.INSERT) {
            replaceEntityProperty(parameter, loginId, sqlCommandType);
        }


        return invocation.proceed();
    }


    private void replaceEntityProperty(Object parameter, String loginId, SqlCommandType sqlCommandType) {
        if (parameter instanceof Map) {
            replaceMap((Map) parameter, loginId, sqlCommandType);
        } else {
            replace(parameter, loginId, sqlCommandType);
        }
    }


    private void replaceMap(Map parameter, String loginId, SqlCommandType sqlCommandType) {
        for (Object var : parameter.values()) {
            replace(var, loginId, sqlCommandType);
        }
    }


    private void replace(Object parameter, String loginId, SqlCommandType sqlCommandType) {
        if (sqlCommandType == SqlCommandType.INSERT) {
            dealInsert(parameter, loginId);
        } else if (sqlCommandType == SqlCommandType.UPDATE) {
            dealUpdate(parameter, loginId);
        }
    }


    private void dealUpdate(Object parameter, String loginId) {
        List<Field> allFields = getAllFields(parameter);
        for (Field field : allFields) {
            try {
                if (Modifier.isFinal(field.getModifiers())) {
                    continue;
                }
                field.setAccessible(true);
                Object value = field.get(parameter);
                if (Objects.nonNull(value)) {
                    continue;
                }


                if ("updateBy".equals(field.getName())) {
                    field.set(parameter, loginId);
                } else if ("updateTime".equals(field.getName())) {
                    field.set(parameter, new Date());
                }
                field.setAccessible(false);
            } catch (Exception e) {
                log.error("Error updating field: " + field.getName(), e);
            }
        }
    }


    private void dealInsert(Object parameter, String loginId) {
        List<Field> allFields = getAllFields(parameter);
        for (Field field : allFields) {
            try {
                if (Modifier.isFinal(field.getModifiers())) {
                    continue;
                }
                field.setAccessible(true);
                Object value = field.get(parameter);
                if (Objects.nonNull(value)) {
                    continue;
                }


                if ("isDeleted".equals(field.getName())) {
                    field.set(parameter, 0);
                } else if ("createdBy".equals(field.getName())) {
                    field.set(parameter, loginId);
                } else if ("createdTime".equals(field.getName())) {
                    field.set(parameter, new Date());
                }
                field.setAccessible(false);
            } catch (Exception e) {
                log.error("Error inserting field: " + field.getName(), e);
            }
        }
    }


    private List<Field> getAllFields(Object object) {
        List<Field> fields = new ArrayList<>();
        Class<?> clazz = object.getClass();
        while (clazz!= null) {
            for (Field field : clazz.getDeclaredFields()) {
                fields.add(field);
            }
            clazz = clazz.getSuperclass();
        }
        return fields;
    }


    public Object plugin(Object target) {
        if (target instanceof Executor) {
            return Plugin.wrap(target, this);
        }
        return target;
    }


    public void setProperties(Properties properties) {
        // 可根据需要设置属性
    }
}